home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / platform.py < prev    next >
Text File  |  2009-11-02  |  52KB  |  1,590 lines

  1. #! /usr/bin/python2.6
  2.  
  3. """ This module tries to retrieve as much platform-identifying data as
  4.     possible. It makes this information available via function APIs.
  5.  
  6.     If called from the command line, it prints the platform
  7.     information concatenated as single string to stdout. The output
  8.     format is useable as part of a filename.
  9.  
  10. """
  11. #    This module is maintained by Marc-Andre Lemburg <mal@egenix.com>.
  12. #    If you find problems, please submit bug reports/patches via the
  13. #    Python SourceForge Project Page and assign them to "lemburg".
  14. #
  15. #    Note: Please keep this module compatible to Python 1.5.2.
  16. #
  17. #    Still needed:
  18. #    * more support for WinCE
  19. #    * support for MS-DOS (PythonDX ?)
  20. #    * support for Amiga and other still unsupported platforms running Python
  21. #    * support for additional Linux distributions
  22. #
  23. #    Many thanks to all those who helped adding platform-specific
  24. #    checks (in no particular order):
  25. #
  26. #      Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,
  27. #      Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef
  28. #      Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg
  29. #      Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark
  30. #      Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),
  31. #      Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter
  32. #
  33. #    History:
  34. #
  35. #    <see CVS and SVN checkin messages for history>
  36. #
  37. #    1.0.6 - added linux_distribution()
  38. #    1.0.5 - fixed Java support to allow running the module on Jython
  39. #    1.0.4 - added IronPython support
  40. #    1.0.3 - added normalization of Windows system name
  41. #    1.0.2 - added more Windows support
  42. #    1.0.1 - reformatted to make doc.py happy
  43. #    1.0.0 - reformatted a bit and checked into Python CVS
  44. #    0.8.0 - added sys.version parser and various new access
  45. #            APIs (python_version(), python_compiler(), etc.)
  46. #    0.7.2 - fixed architecture() to use sizeof(pointer) where available
  47. #    0.7.1 - added support for Caldera OpenLinux
  48. #    0.7.0 - some fixes for WinCE; untabified the source file
  49. #    0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and
  50. #            vms_lib.getsyi() configured
  51. #    0.6.1 - added code to prevent 'uname -p' on platforms which are
  52. #            known not to support it
  53. #    0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;
  54. #            did some cleanup of the interfaces - some APIs have changed
  55. #    0.5.5 - fixed another type in the MacOS code... should have
  56. #            used more coffee today ;-)
  57. #    0.5.4 - fixed a few typos in the MacOS code
  58. #    0.5.3 - added experimental MacOS support; added better popen()
  59. #            workarounds in _syscmd_ver() -- still not 100% elegant
  60. #            though
  61. #    0.5.2 - fixed uname() to return '' instead of 'unknown' in all
  62. #            return values (the system uname command tends to return
  63. #            'unknown' instead of just leaving the field emtpy)
  64. #    0.5.1 - included code for slackware dist; added exception handlers
  65. #            to cover up situations where platforms don't have os.popen
  66. #            (e.g. Mac) or fail on socket.gethostname(); fixed libc
  67. #            detection RE
  68. #    0.5.0 - changed the API names referring to system commands to *syscmd*;
  69. #            added java_ver(); made syscmd_ver() a private
  70. #            API (was system_ver() in previous versions) -- use uname()
  71. #            instead; extended the win32_ver() to also return processor
  72. #            type information
  73. #    0.4.0 - added win32_ver() and modified the platform() output for WinXX
  74. #    0.3.4 - fixed a bug in _follow_symlinks()
  75. #    0.3.3 - fixed popen() and "file" command invokation bugs
  76. #    0.3.2 - added architecture() API and support for it in platform()
  77. #    0.3.1 - fixed syscmd_ver() RE to support Windows NT
  78. #    0.3.0 - added system alias support
  79. #    0.2.3 - removed 'wince' again... oh well.
  80. #    0.2.2 - added 'wince' to syscmd_ver() supported platforms
  81. #    0.2.1 - added cache logic and changed the platform string format
  82. #    0.2.0 - changed the API to use functions instead of module globals
  83. #            since some action take too long to be run on module import
  84. #    0.1.0 - first release
  85. #
  86. #    You can always get the latest version of this module at:
  87. #
  88. #             http://www.egenix.com/files/python/platform.py
  89. #
  90. #    If that URL should fail, try contacting the author.
  91.  
  92. __copyright__ = """
  93.     Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
  94.     Copyright (c) 2000-2008, eGenix.com Software GmbH; mailto:info@egenix.com
  95.  
  96.     Permission to use, copy, modify, and distribute this software and its
  97.     documentation for any purpose and without fee or royalty is hereby granted,
  98.     provided that the above copyright notice appear in all copies and that
  99.     both that copyright notice and this permission notice appear in
  100.     supporting documentation or portions thereof, including modifications,
  101.     that you make.
  102.  
  103.     EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO
  104.     THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  105.     FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
  106.     INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  107.     FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  108.     NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  109.     WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
  110.  
  111. """
  112.  
  113. __version__ = '1.0.6'
  114.  
  115. import sys,string,os,re
  116.  
  117. ### Platform specific APIs
  118.  
  119. _libc_search = re.compile(r'(__libc_init)'
  120.                           '|'
  121.                           '(GLIBC_([0-9.]+))'
  122.                           '|'
  123.                           '(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)')
  124.  
  125. def libc_ver(executable=sys.executable,lib='',version='',
  126.  
  127.              chunksize=2048):
  128.  
  129.     """ Tries to determine the libc version that the file executable
  130.         (which defaults to the Python interpreter) is linked against.
  131.  
  132.         Returns a tuple of strings (lib,version) which default to the
  133.         given parameters in case the lookup fails.
  134.  
  135.         Note that the function has intimate knowledge of how different
  136.         libc versions add symbols to the executable and thus is probably
  137.         only useable for executables compiled using gcc.
  138.  
  139.         The file is read and scanned in chunks of chunksize bytes.
  140.  
  141.     """
  142.     if hasattr(os.path, 'realpath'):
  143.         # Python 2.2 introduced os.path.realpath(); it is used
  144.         # here to work around problems with Cygwin not being
  145.         # able to open symlinks for reading
  146.         executable = os.path.realpath(executable)
  147.     f = open(executable,'rb')
  148.     binary = f.read(chunksize)
  149.     pos = 0
  150.     while 1:
  151.         m = _libc_search.search(binary,pos)
  152.         if not m:
  153.             binary = f.read(chunksize)
  154.             if not binary:
  155.                 break
  156.             pos = 0
  157.             continue
  158.         libcinit,glibc,glibcversion,so,threads,soversion = m.groups()
  159.         if libcinit and not lib:
  160.             lib = 'libc'
  161.         elif glibc:
  162.             if lib != 'glibc':
  163.                 lib = 'glibc'
  164.                 version = glibcversion
  165.             elif glibcversion > version:
  166.                 version = glibcversion
  167.         elif so:
  168.             if lib != 'glibc':
  169.                 lib = 'libc'
  170.                 if soversion > version:
  171.                     version = soversion
  172.                 if threads and version[-len(threads):] != threads:
  173.                     version = version + threads
  174.         pos = m.end()
  175.     f.close()
  176.     return lib,version
  177.  
  178. def _dist_try_harder(distname,version,id):
  179.  
  180.     """ Tries some special tricks to get the distribution
  181.         information in case the default method fails.
  182.  
  183.         Currently supports older SuSE Linux, Caldera OpenLinux and
  184.         Slackware Linux distributions.
  185.  
  186.     """
  187.     if os.path.exists('/var/adm/inst-log/info'):
  188.         # SuSE Linux stores distribution information in that file
  189.         info = open('/var/adm/inst-log/info').readlines()
  190.         distname = 'SuSE'
  191.         for line in info:
  192.             tv = string.split(line)
  193.             if len(tv) == 2:
  194.                 tag,value = tv
  195.             else:
  196.                 continue
  197.             if tag == 'MIN_DIST_VERSION':
  198.                 version = string.strip(value)
  199.             elif tag == 'DIST_IDENT':
  200.                 values = string.split(value,'-')
  201.                 id = values[2]
  202.         return distname,version,id
  203.  
  204.     if os.path.exists('/etc/.installed'):
  205.         # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
  206.         info = open('/etc/.installed').readlines()
  207.         for line in info:
  208.             pkg = string.split(line,'-')
  209.             if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
  210.                 # XXX does Caldera support non Intel platforms ? If yes,
  211.                 #     where can we find the needed id ?
  212.                 return 'OpenLinux',pkg[1],id
  213.  
  214.     if os.path.isdir('/usr/lib/setup'):
  215.         # Check for slackware verson tag file (thanks to Greg Andruk)
  216.         verfiles = os.listdir('/usr/lib/setup')
  217.         for n in range(len(verfiles)-1, -1, -1):
  218.             if verfiles[n][:14] != 'slack-version-':
  219.                 del verfiles[n]
  220.         if verfiles:
  221.             verfiles.sort()
  222.             distname = 'slackware'
  223.             version = verfiles[-1][14:]
  224.             return distname,version,id
  225.  
  226.     return distname,version,id
  227.  
  228. _release_filename = re.compile(r'(\w+)[-_](release|version)')
  229. _lsb_release_version = re.compile(r'(.+)'
  230.                                    ' release '
  231.                                    '([\d.]+)'
  232.                                    '[^(]*(?:\((.+)\))?')
  233. _release_version = re.compile(r'([^0-9]+)'
  234.                                '(?: release )?'
  235.                                '([\d.]+)'
  236.                                '[^(]*(?:\((.+)\))?')
  237.  
  238. # See also http://www.novell.com/coolsolutions/feature/11251.html
  239. # and http://linuxmafia.com/faq/Admin/release-files.html
  240. # and http://data.linux-ntfs.org/rpm/whichrpm
  241. # and http://www.die.net/doc/linux/man/man1/lsb_release.1.html
  242.  
  243. _supported_dists = (
  244.     'SuSE', 'debian', 'fedora', 'redhat', 'centos',
  245.     'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo',
  246.     'UnitedLinux', 'turbolinux')
  247.  
  248. def _parse_release_file(firstline):
  249.  
  250.     # Parse the first line
  251.     m = _lsb_release_version.match(firstline)
  252.     if m is not None:
  253.         # LSB format: "distro release x.x (codename)"
  254.         return tuple(m.groups())
  255.  
  256.     # Pre-LSB format: "distro x.x (codename)"
  257.     m = _release_version.match(firstline)
  258.     if m is not None:
  259.         return tuple(m.groups())
  260.  
  261.     # Unkown format... take the first two words
  262.     l = string.split(string.strip(firstline))
  263.     if l:
  264.         version = l[0]
  265.         if len(l) > 1:
  266.             id = l[1]
  267.         else:
  268.             id = ''
  269.     return '', version, id
  270.  
  271. def _test_parse_release_file():
  272.  
  273.     for input, output in (
  274.         # Examples of release file contents:
  275.         ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64'))
  276.         ('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64'))
  277.         ('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586'))
  278.         ('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux'))
  279.         ('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche'))
  280.         ('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike'))
  281.         ('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant'))
  282.         ('CentOS release 4', ('CentOS', '4', None))
  283.         ('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia'))
  284.         ):
  285.         parsed = _parse_release_file(input)
  286.         if parsed != output:
  287.             print (input, parsed)
  288.  
  289. _distributor_id_file_re = re.compile("(?:DISTRIB_ID\s*=)\s*(.*)", re.I)
  290. _release_file_re = re.compile("(?:DISTRIB_RELEASE\s*=)\s*(.*)", re.I)
  291. _codename_file_re = re.compile("(?:DISTRIB_CODENAME\s*=)\s*(.*)", re.I)
  292.  
  293. def linux_distribution(distname='', version='', id='',
  294.  
  295.                        supported_dists=_supported_dists,
  296.                        full_distribution_name=1):
  297.  
  298.     """ Tries to determine the name of the Linux OS distribution name.
  299.  
  300.         The function first looks for a distribution release file in
  301.         /etc and then reverts to _dist_try_harder() in case no
  302.         suitable files are found.
  303.  
  304.         supported_dists may be given to define the set of Linux
  305.         distributions to look for. It defaults to a list of currently
  306.         supported Linux distributions identified by their release file
  307.         name.
  308.  
  309.         If full_distribution_name is true (default), the full
  310.         distribution read from the OS is returned. Otherwise the short
  311.         name taken from supported_dists is used.
  312.  
  313.         Returns a tuple (distname,version,id) which default to the
  314.         args given as parameters.
  315.  
  316.     """
  317.     # check for the Debian/Ubuntu /etc/lsb-release file first, needed so
  318.     # that the distribution doesn't get identified as Debian.
  319.     try:
  320.         etclsbrel = open("/etc/lsb-release", "rU")
  321.         for line in etclsbrel:
  322.             m = _distributor_id_file_re.search(line)
  323.             if m:
  324.                 _u_distname = m.group(1).strip()
  325.             m = _release_file_re.search(line)
  326.             if m:
  327.                 _u_version = m.group(1).strip()
  328.             m = _codename_file_re.search(line)
  329.             if m:
  330.                 _u_id = m.group(1).strip()
  331.         if _u_distname and _u_version:
  332.             return (_u_distname, _u_version, _u_id)
  333.     except (EnvironmentError, UnboundLocalError):
  334.             pass
  335.  
  336.     try:
  337.         etc = os.listdir('/etc')
  338.     except os.error:
  339.         # Probably not a Unix system
  340.         return distname,version,id
  341.     etc.sort()
  342.     for file in etc:
  343.         m = _release_filename.match(file)
  344.         if m is not None:
  345.             _distname,dummy = m.groups()
  346.             if _distname in supported_dists:
  347.                 distname = _distname
  348.                 break
  349.     else:
  350.         return _dist_try_harder(distname,version,id)
  351.  
  352.     # Read the first line
  353.     f = open('/etc/'+file, 'r')
  354.     firstline = f.readline()
  355.     f.close()
  356.     _distname, _version, _id = _parse_release_file(firstline)
  357.  
  358.     if _distname and full_distribution_name:
  359.         distname = _distname
  360.     if _version:
  361.         version = _version
  362.     if _id:
  363.         id = _id
  364.     return distname, version, id
  365.  
  366. # To maintain backwards compatibility:
  367.  
  368. def dist(distname='',version='',id='',
  369.  
  370.          supported_dists=_supported_dists):
  371.  
  372.     """ Tries to determine the name of the Linux OS distribution name.
  373.  
  374.         The function first looks for a distribution release file in
  375.         /etc and then reverts to _dist_try_harder() in case no
  376.         suitable files are found.
  377.  
  378.         Returns a tuple (distname,version,id) which default to the
  379.         args given as parameters.
  380.  
  381.     """
  382.     return linux_distribution(distname, version, id,
  383.                               supported_dists=supported_dists,
  384.                               full_distribution_name=0)
  385.  
  386. class _popen:
  387.  
  388.     """ Fairly portable (alternative) popen implementation.
  389.  
  390.         This is mostly needed in case os.popen() is not available, or
  391.         doesn't work as advertised, e.g. in Win9X GUI programs like
  392.         PythonWin or IDLE.
  393.  
  394.         Writing to the pipe is currently not supported.
  395.  
  396.     """
  397.     tmpfile = ''
  398.     pipe = None
  399.     bufsize = None
  400.     mode = 'r'
  401.  
  402.     def __init__(self,cmd,mode='r',bufsize=None):
  403.  
  404.         if mode != 'r':
  405.             raise ValueError,'popen()-emulation only supports read mode'
  406.         import tempfile
  407.         self.tmpfile = tmpfile = tempfile.mktemp()
  408.         os.system(cmd + ' > %s' % tmpfile)
  409.         self.pipe = open(tmpfile,'rb')
  410.         self.bufsize = bufsize
  411.         self.mode = mode
  412.  
  413.     def read(self):
  414.  
  415.         return self.pipe.read()
  416.  
  417.     def readlines(self):
  418.  
  419.         if self.bufsize is not None:
  420.             return self.pipe.readlines()
  421.  
  422.     def close(self,
  423.  
  424.               remove=os.unlink,error=os.error):
  425.  
  426.         if self.pipe:
  427.             rc = self.pipe.close()
  428.         else:
  429.             rc = 255
  430.         if self.tmpfile:
  431.             try:
  432.                 remove(self.tmpfile)
  433.             except error:
  434.                 pass
  435.         return rc
  436.  
  437.     # Alias
  438.     __del__ = close
  439.  
  440. def popen(cmd, mode='r', bufsize=None):
  441.  
  442.     """ Portable popen() interface.
  443.     """
  444.     # Find a working popen implementation preferring win32pipe.popen
  445.     # over os.popen over _popen
  446.     popen = None
  447.     if os.environ.get('OS','') == 'Windows_NT':
  448.         # On NT win32pipe should work; on Win9x it hangs due to bugs
  449.         # in the MS C lib (see MS KnowledgeBase article Q150956)
  450.         try:
  451.             import win32pipe
  452.         except ImportError:
  453.             pass
  454.         else:
  455.             popen = win32pipe.popen
  456.     if popen is None:
  457.         if hasattr(os,'popen'):
  458.             popen = os.popen
  459.             # Check whether it works... it doesn't in GUI programs
  460.             # on Windows platforms
  461.             if sys.platform == 'win32': # XXX Others too ?
  462.                 try:
  463.                     popen('')
  464.                 except os.error:
  465.                     popen = _popen
  466.         else:
  467.             popen = _popen
  468.     if bufsize is None:
  469.         return popen(cmd,mode)
  470.     else:
  471.         return popen(cmd,mode,bufsize)
  472.  
  473. def _norm_version(version, build=''):
  474.  
  475.     """ Normalize the version and build strings and return a single
  476.         version string using the format major.minor.build (or patchlevel).
  477.     """
  478.     l = string.split(version,'.')
  479.     if build:
  480.         l.append(build)
  481.     try:
  482.         ints = map(int,l)
  483.     except ValueError:
  484.         strings = l
  485.     else:
  486.         strings = map(str,ints)
  487.     version = string.join(strings[:3],'.')
  488.     return version
  489.  
  490. _ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
  491.                          '.*'
  492.                          'Version ([\d.]+))')
  493.  
  494. def _syscmd_ver(system='', release='', version='',
  495.  
  496.                supported_platforms=('win32','win16','dos','os2')):
  497.  
  498.     """ Tries to figure out the OS version used and returns
  499.         a tuple (system,release,version).
  500.  
  501.         It uses the "ver" shell command for this which is known
  502.         to exists on Windows, DOS and OS/2. XXX Others too ?
  503.  
  504.         In case this fails, the given parameters are used as
  505.         defaults.
  506.  
  507.     """
  508.     if sys.platform not in supported_platforms:
  509.         return system,release,version
  510.  
  511.     # Try some common cmd strings
  512.     for cmd in ('ver','command /c ver','cmd /c ver'):
  513.         try:
  514.             pipe = popen(cmd)
  515.             info = pipe.read()
  516.             if pipe.close():
  517.                 raise os.error,'command failed'
  518.             # XXX How can I supress shell errors from being written
  519.             #     to stderr ?
  520.         except os.error,why:
  521.             #print 'Command %s failed: %s' % (cmd,why)
  522.             continue
  523.         except IOError,why:
  524.             #print 'Command %s failed: %s' % (cmd,why)
  525.             continue
  526.         else:
  527.             break
  528.     else:
  529.         return system,release,version
  530.  
  531.     # Parse the output
  532.     info = string.strip(info)
  533.     m = _ver_output.match(info)
  534.     if m is not None:
  535.         system,release,version = m.groups()
  536.         # Strip trailing dots from version and release
  537.         if release[-1] == '.':
  538.             release = release[:-1]
  539.         if version[-1] == '.':
  540.             version = version[:-1]
  541.         # Normalize the version and build strings (eliminating additional
  542.         # zeros)
  543.         version = _norm_version(version)
  544.     return system,release,version
  545.  
  546. def _win32_getvalue(key,name,default=''):
  547.  
  548.     """ Read a value for name from the registry key.
  549.  
  550.         In case this fails, default is returned.
  551.  
  552.     """
  553.     try:
  554.         # Use win32api if available
  555.         from win32api import RegQueryValueEx
  556.     except ImportError:
  557.         # On Python 2.0 and later, emulate using _winreg
  558.         import _winreg
  559.         RegQueryValueEx = _winreg.QueryValueEx
  560.     try:
  561.         return RegQueryValueEx(key,name)
  562.     except:
  563.         return default
  564.  
  565. def win32_ver(release='',version='',csd='',ptype=''):
  566.  
  567.     """ Get additional version information from the Windows Registry
  568.         and return a tuple (version,csd,ptype) referring to version
  569.         number, CSD level and OS type (multi/single
  570.         processor).
  571.  
  572.         As a hint: ptype returns 'Uniprocessor Free' on single
  573.         processor NT machines and 'Multiprocessor Free' on multi
  574.         processor machines. The 'Free' refers to the OS version being
  575.         free of debugging code. It could also state 'Checked' which
  576.         means the OS version uses debugging code, i.e. code that
  577.         checks arguments, ranges, etc. (Thomas Heller).
  578.  
  579.         Note: this function works best with Mark Hammond's win32
  580.         package installed, but also on Python 2.3 and later. It
  581.         obviously only runs on Win32 compatible platforms.
  582.  
  583.     """
  584.     # XXX Is there any way to find out the processor type on WinXX ?
  585.     # XXX Is win32 available on Windows CE ?
  586.     #
  587.     # Adapted from code posted by Karl Putland to comp.lang.python.
  588.     #
  589.     # The mappings between reg. values and release names can be found
  590.     # here: http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp
  591.  
  592.     # Import the needed APIs
  593.     try:
  594.         import win32api
  595.         from win32api import RegQueryValueEx, RegOpenKeyEx, \
  596.              RegCloseKey, GetVersionEx
  597.         from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \
  598.              VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION
  599.     except ImportError:
  600.         # Emulate the win32api module using Python APIs
  601.         try:
  602.             sys.getwindowsversion
  603.         except AttributeError:
  604.             # No emulation possible, so return the defaults...
  605.             return release,version,csd,ptype
  606.         else:
  607.             # Emulation using _winreg (added in Python 2.0) and
  608.             # sys.getwindowsversion() (added in Python 2.3)
  609.             import _winreg
  610.             GetVersionEx = sys.getwindowsversion
  611.             RegQueryValueEx = _winreg.QueryValueEx
  612.             RegOpenKeyEx = _winreg.OpenKeyEx
  613.             RegCloseKey = _winreg.CloseKey
  614.             HKEY_LOCAL_MACHINE = _winreg.HKEY_LOCAL_MACHINE
  615.             VER_PLATFORM_WIN32_WINDOWS = 1
  616.             VER_PLATFORM_WIN32_NT = 2
  617.             VER_NT_WORKSTATION = 1
  618.  
  619.     # Find out the registry key and some general version infos
  620.     maj,min,buildno,plat,csd = GetVersionEx()
  621.     version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)
  622.     if csd[:13] == 'Service Pack ':
  623.         csd = 'SP' + csd[13:]
  624.     if plat == VER_PLATFORM_WIN32_WINDOWS:
  625.         regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
  626.         # Try to guess the release name
  627.         if maj == 4:
  628.             if min == 0:
  629.                 release = '95'
  630.             elif min == 10:
  631.                 release = '98'
  632.             elif min == 90:
  633.                 release = 'Me'
  634.             else:
  635.                 release = 'postMe'
  636.         elif maj == 5:
  637.             release = '2000'
  638.     elif plat == VER_PLATFORM_WIN32_NT:
  639.         regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
  640.         if maj <= 4:
  641.             release = 'NT'
  642.         elif maj == 5:
  643.             if min == 0:
  644.                 release = '2000'
  645.             elif min == 1:
  646.                 release = 'XP'
  647.             elif min == 2:
  648.                 release = '2003Server'
  649.             else:
  650.                 release = 'post2003'
  651.         elif maj == 6:
  652.             if min == 0:
  653.                 # Per http://msdn2.microsoft.com/en-us/library/ms724429.aspx
  654.                 try:
  655.                     productType = GetVersionEx(1)[8]
  656.                 except TypeError:
  657.                     # sys.getwindowsversion() doesn't take any arguments, so
  658.                     # we cannot detect 2008 Server that way.
  659.                     # XXX Add some other means of detecting 2008 Server ?!
  660.                     release = 'Vista'
  661.                 else:
  662.                     if productType == VER_NT_WORKSTATION:
  663.                         release = 'Vista'
  664.                     else:
  665.                         release = '2008Server'
  666.             else:
  667.                 release = 'post2008Server'
  668.     else:
  669.         if not release:
  670.             # E.g. Win3.1 with win32s
  671.             release = '%i.%i' % (maj,min)
  672.         return release,version,csd,ptype
  673.  
  674.     # Open the registry key
  675.     try:
  676.         keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
  677.         # Get a value to make sure the key exists...
  678.         RegQueryValueEx(keyCurVer, 'SystemRoot')
  679.     except:
  680.         return release,version,csd,ptype
  681.  
  682.     # Parse values
  683.     #subversion = _win32_getvalue(keyCurVer,
  684.     #                            'SubVersionNumber',
  685.     #                            ('',1))[0]
  686.     #if subversion:
  687.     #   release = release + subversion # 95a, 95b, etc.
  688.     build = _win32_getvalue(keyCurVer,
  689.                             'CurrentBuildNumber',
  690.                             ('',1))[0]
  691.     ptype = _win32_getvalue(keyCurVer,
  692.                            'CurrentType',
  693.                            (ptype,1))[0]
  694.  
  695.     # Normalize version
  696.     version = _norm_version(version,build)
  697.  
  698.     # Close key
  699.     RegCloseKey(keyCurVer)
  700.     return release,version,csd,ptype
  701.  
  702. def _mac_ver_lookup(selectors,default=None):
  703.  
  704.     from gestalt import gestalt
  705.     import MacOS
  706.     l = []
  707.     append = l.append
  708.     for selector in selectors:
  709.         try:
  710.             append(gestalt(selector))
  711.         except (RuntimeError, MacOS.Error):
  712.             append(default)
  713.     return l
  714.  
  715. def _bcd2str(bcd):
  716.  
  717.     return hex(bcd)[2:]
  718.  
  719. def mac_ver(release='',versioninfo=('','',''),machine=''):
  720.  
  721.     """ Get MacOS version information and return it as tuple (release,
  722.         versioninfo, machine) with versioninfo being a tuple (version,
  723.         dev_stage, non_release_version).
  724.  
  725.         Entries which cannot be determined are set to the paramter values
  726.         which default to ''. All tuple entries are strings.
  727.  
  728.         Thanks to Mark R. Levinson for mailing documentation links and
  729.         code examples for this function. Documentation for the
  730.         gestalt() API is available online at:
  731.  
  732.            http://www.rgaros.nl/gestalt/
  733.  
  734.     """
  735.     # Check whether the version info module is available
  736.     try:
  737.         import gestalt
  738.         import MacOS
  739.     except ImportError:
  740.         return release,versioninfo,machine
  741.     # Get the infos
  742.     sysv,sysu,sysa = _mac_ver_lookup(('sysv','sysu','sysa'))
  743.     # Decode the infos
  744.     if sysv:
  745.         major = (sysv & 0xFF00) >> 8
  746.         minor = (sysv & 0x00F0) >> 4
  747.         patch = (sysv & 0x000F)
  748.  
  749.         if (major, minor) >= (10, 4):
  750.             # the 'sysv' gestald cannot return patchlevels
  751.             # higher than 9. Apple introduced 3 new
  752.             # gestalt codes in 10.4 to deal with this
  753.             # issue (needed because patch levels can
  754.             # run higher than 9, such as 10.4.11)
  755.             major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))
  756.             release = '%i.%i.%i' %(major, minor, patch)
  757.         else:
  758.             release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
  759.  
  760.     if sysu:
  761.         # NOTE: this block is left as documentation of the
  762.         # intention of this function, the 'sysu' gestalt is no
  763.         # longer available and there are no alternatives.
  764.         major =  int((sysu & 0xFF000000L) >> 24)
  765.         minor =  (sysu & 0x00F00000) >> 20
  766.         bugfix = (sysu & 0x000F0000) >> 16
  767.         stage =  (sysu & 0x0000FF00) >> 8
  768.         nonrel = (sysu & 0x000000FF)
  769.         version = '%s.%i.%i' % (_bcd2str(major),minor,bugfix)
  770.         nonrel = _bcd2str(nonrel)
  771.         stage = {0x20:'development',
  772.                  0x40:'alpha',
  773.                  0x60:'beta',
  774.                  0x80:'final'}.get(stage,'')
  775.         versioninfo = (version,stage,nonrel)
  776.  
  777.  
  778.     if sysa:
  779.         machine = {0x1: '68k',
  780.                    0x2: 'PowerPC',
  781.                    0xa: 'i386'}.get(sysa,'')
  782.     return release,versioninfo,machine
  783.  
  784. def _java_getprop(name,default):
  785.  
  786.     from java.lang import System
  787.     try:
  788.         value = System.getProperty(name)
  789.         if value is None:
  790.             return default
  791.         return value
  792.     except AttributeError:
  793.         return default
  794.  
  795. def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
  796.  
  797.     """ Version interface for Jython.
  798.  
  799.         Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
  800.         a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
  801.         tuple (os_name,os_version,os_arch).
  802.  
  803.         Values which cannot be determined are set to the defaults
  804.         given as parameters (which all default to '').
  805.  
  806.     """
  807.     # Import the needed APIs
  808.     try:
  809.         import java.lang
  810.     except ImportError:
  811.         return release,vendor,vminfo,osinfo
  812.  
  813.     vendor = _java_getprop('java.vendor', vendor)
  814.     release = _java_getprop('java.version', release)
  815.     vm_name, vm_release, vm_vendor = vminfo
  816.     vm_name = _java_getprop('java.vm.name', vm_name)
  817.     vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
  818.     vm_release = _java_getprop('java.vm.version', vm_release)
  819.     vminfo = vm_name, vm_release, vm_vendor
  820.     os_name, os_version, os_arch = osinfo
  821.     os_arch = _java_getprop('java.os.arch', os_arch)
  822.     os_name = _java_getprop('java.os.name', os_name)
  823.     os_version = _java_getprop('java.os.version', os_version)
  824.     osinfo = os_name, os_version, os_arch
  825.  
  826.     return release, vendor, vminfo, osinfo
  827.  
  828. ### System name aliasing
  829.  
  830. def system_alias(system,release,version):
  831.  
  832.     """ Returns (system,release,version) aliased to common
  833.         marketing names used for some systems.
  834.  
  835.         It also does some reordering of the information in some cases
  836.         where it would otherwise cause confusion.
  837.  
  838.     """
  839.     if system == 'Rhapsody':
  840.         # Apple's BSD derivative
  841.         # XXX How can we determine the marketing release number ?
  842.         return 'MacOS X Server',system+release,version
  843.  
  844.     elif system == 'SunOS':
  845.         # Sun's OS
  846.         if release < '5':
  847.             # These releases use the old name SunOS
  848.             return system,release,version
  849.         # Modify release (marketing release = SunOS release - 3)
  850.         l = string.split(release,'.')
  851.         if l:
  852.             try:
  853.                 major = int(l[0])
  854.             except ValueError:
  855.                 pass
  856.             else:
  857.                 major = major - 3
  858.                 l[0] = str(major)
  859.                 release = string.join(l,'.')
  860.         if release < '6':
  861.             system = 'Solaris'
  862.         else:
  863.             # XXX Whatever the new SunOS marketing name is...
  864.             system = 'Solaris'
  865.  
  866.     elif system == 'IRIX64':
  867.         # IRIX reports IRIX64 on platforms with 64-bit support; yet it
  868.         # is really a version and not a different platform, since 32-bit
  869.         # apps are also supported..
  870.         system = 'IRIX'
  871.         if version:
  872.             version = version + ' (64bit)'
  873.         else:
  874.             version = '64bit'
  875.  
  876.     elif system in ('win32','win16'):
  877.         # In case one of the other tricks
  878.         system = 'Windows'
  879.  
  880.     return system,release,version
  881.  
  882. ### Various internal helpers
  883.  
  884. def _platform(*args):
  885.  
  886.     """ Helper to format the platform string in a filename
  887.         compatible format e.g. "system-version-machine".
  888.     """
  889.     # Format the platform string
  890.     platform = string.join(
  891.         map(string.strip,
  892.             filter(len, args)),
  893.         '-')
  894.  
  895.     # Cleanup some possible filename obstacles...
  896.     replace = string.replace
  897.     platform = replace(platform,' ','_')
  898.     platform = replace(platform,'/','-')
  899.     platform = replace(platform,'\\','-')
  900.     platform = replace(platform,':','-')
  901.     platform = replace(platform,';','-')
  902.     platform = replace(platform,'"','-')
  903.     platform = replace(platform,'(','-')
  904.     platform = replace(platform,')','-')
  905.  
  906.     # No need to report 'unknown' information...
  907.     platform = replace(platform,'unknown','')
  908.  
  909.     # Fold '--'s and remove trailing '-'
  910.     while 1:
  911.         cleaned = replace(platform,'--','-')
  912.         if cleaned == platform:
  913.             break
  914.         platform = cleaned
  915.     while platform[-1] == '-':
  916.         platform = platform[:-1]
  917.  
  918.     return platform
  919.  
  920. def _node(default=''):
  921.  
  922.     """ Helper to determine the node name of this machine.
  923.     """
  924.     try:
  925.         import socket
  926.     except ImportError:
  927.         # No sockets...
  928.         return default
  929.     try:
  930.         return socket.gethostname()
  931.     except socket.error:
  932.         # Still not working...
  933.         return default
  934.  
  935. # os.path.abspath is new in Python 1.5.2:
  936. if not hasattr(os.path,'abspath'):
  937.  
  938.     def _abspath(path,
  939.  
  940.                  isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
  941.                  normpath=os.path.normpath):
  942.  
  943.         if not isabs(path):
  944.             path = join(getcwd(), path)
  945.         return normpath(path)
  946.  
  947. else:
  948.  
  949.     _abspath = os.path.abspath
  950.  
  951. def _follow_symlinks(filepath):
  952.  
  953.     """ In case filepath is a symlink, follow it until a
  954.         real file is reached.
  955.     """
  956.     filepath = _abspath(filepath)
  957.     while os.path.islink(filepath):
  958.         filepath = os.path.normpath(
  959.             os.path.join(os.path.dirname(filepath),os.readlink(filepath)))
  960.     return filepath
  961.  
  962. def _syscmd_uname(option,default=''):
  963.  
  964.     """ Interface to the system's uname command.
  965.     """
  966.     if sys.platform in ('dos','win32','win16','os2'):
  967.         # XXX Others too ?
  968.         return default
  969.     try:
  970.         f = os.popen('uname %s 2> /dev/null' % option)
  971.     except (AttributeError,os.error):
  972.         return default
  973.     output = string.strip(f.read())
  974.     rc = f.close()
  975.     if not output or rc:
  976.         return default
  977.     else:
  978.         return output
  979.  
  980. def _syscmd_file(target,default=''):
  981.  
  982.     """ Interface to the system's file command.
  983.  
  984.         The function uses the -b option of the file command to have it
  985.         ommit the filename in its output and if possible the -L option
  986.         to have the command follow symlinks. It returns default in
  987.         case the command should fail.
  988.  
  989.     """
  990.     if sys.platform in ('dos','win32','win16','os2'):
  991.         # XXX Others too ?
  992.         return default
  993.     target = _follow_symlinks(target)
  994.     try:
  995.         f = os.popen('file "%s" 2> /dev/null' % target)
  996.     except (AttributeError,os.error):
  997.         return default
  998.     output = string.strip(f.read())
  999.     rc = f.close()
  1000.     if not output or rc:
  1001.         return default
  1002.     else:
  1003.         return output
  1004.  
  1005. ### Information about the used architecture
  1006.  
  1007. # Default values for architecture; non-empty strings override the
  1008. # defaults given as parameters
  1009. _default_architecture = {
  1010.     'win32': ('','WindowsPE'),
  1011.     'win16': ('','Windows'),
  1012.     'dos': ('','MSDOS'),
  1013. }
  1014.  
  1015. _architecture_split = re.compile(r'[\s,]').split
  1016.  
  1017. def architecture(executable=sys.executable,bits='',linkage=''):
  1018.  
  1019.     """ Queries the given executable (defaults to the Python interpreter
  1020.         binary) for various architecture information.
  1021.  
  1022.         Returns a tuple (bits,linkage) which contains information about
  1023.         the bit architecture and the linkage format used for the
  1024.         executable. Both values are returned as strings.
  1025.  
  1026.         Values that cannot be determined are returned as given by the
  1027.         parameter presets. If bits is given as '', the sizeof(pointer)
  1028.         (or sizeof(long) on Python version < 1.5.2) is used as
  1029.         indicator for the supported pointer size.
  1030.  
  1031.         The function relies on the system's "file" command to do the
  1032.         actual work. This is available on most if not all Unix
  1033.         platforms. On some non-Unix platforms where the "file" command
  1034.         does not exist and the executable is set to the Python interpreter
  1035.         binary defaults from _default_architecture are used.
  1036.  
  1037.     """
  1038.     # Use the sizeof(pointer) as default number of bits if nothing
  1039.     # else is given as default.
  1040.     if not bits:
  1041.         import struct
  1042.         try:
  1043.             size = struct.calcsize('P')
  1044.         except struct.error:
  1045.             # Older installations can only query longs
  1046.             size = struct.calcsize('l')
  1047.         bits = str(size*8) + 'bit'
  1048.  
  1049.     # Get data from the 'file' system command
  1050.     if executable:
  1051.         output = _syscmd_file(executable, '')
  1052.     else:
  1053.         output = ''
  1054.  
  1055.     if not output and \
  1056.        executable == sys.executable:
  1057.         # "file" command did not return anything; we'll try to provide
  1058.         # some sensible defaults then...
  1059.         if _default_architecture.has_key(sys.platform):
  1060.             b,l = _default_architecture[sys.platform]
  1061.             if b:
  1062.                 bits = b
  1063.             if l:
  1064.                 linkage = l
  1065.         return bits,linkage
  1066.  
  1067.     # Split the output into a list of strings omitting the filename
  1068.     fileout = _architecture_split(output)[1:]
  1069.  
  1070.     if 'executable' not in fileout:
  1071.         # Format not supported
  1072.         return bits,linkage
  1073.  
  1074.     # Bits
  1075.     if '32-bit' in fileout:
  1076.         bits = '32bit'
  1077.     elif 'N32' in fileout:
  1078.         # On Irix only
  1079.         bits = 'n32bit'
  1080.     elif '64-bit' in fileout:
  1081.         bits = '64bit'
  1082.  
  1083.     # Linkage
  1084.     if 'ELF' in fileout:
  1085.         linkage = 'ELF'
  1086.     elif 'PE' in fileout:
  1087.         # E.g. Windows uses this format
  1088.         if 'Windows' in fileout:
  1089.             linkage = 'WindowsPE'
  1090.         else:
  1091.             linkage = 'PE'
  1092.     elif 'COFF' in fileout:
  1093.         linkage = 'COFF'
  1094.     elif 'MS-DOS' in fileout:
  1095.         linkage = 'MSDOS'
  1096.     else:
  1097.         # XXX the A.OUT format also falls under this class...
  1098.         pass
  1099.  
  1100.     return bits,linkage
  1101.  
  1102. ### Portable uname() interface
  1103.  
  1104. _uname_cache = None
  1105.  
  1106. def uname():
  1107.  
  1108.     """ Fairly portable uname interface. Returns a tuple
  1109.         of strings (system,node,release,version,machine,processor)
  1110.         identifying the underlying platform.
  1111.  
  1112.         Note that unlike the os.uname function this also returns
  1113.         possible processor information as an additional tuple entry.
  1114.  
  1115.         Entries which cannot be determined are set to ''.
  1116.  
  1117.     """
  1118.     global _uname_cache
  1119.     no_os_uname = 0
  1120.  
  1121.     if _uname_cache is not None:
  1122.         return _uname_cache
  1123.  
  1124.     processor = ''
  1125.  
  1126.     # Get some infos from the builtin os.uname API...
  1127.     try:
  1128.         system,node,release,version,machine = os.uname()
  1129.     except AttributeError:
  1130.         no_os_uname = 1
  1131.  
  1132.     if no_os_uname or not filter(None, (system, node, release, version, machine)):
  1133.         # Hmm, no there is either no uname or uname has returned
  1134.         #'unknowns'... we'll have to poke around the system then.
  1135.         if no_os_uname:
  1136.             system = sys.platform
  1137.             release = ''
  1138.             version = ''
  1139.             node = _node()
  1140.             machine = ''
  1141.  
  1142.         use_syscmd_ver = 01
  1143.  
  1144.         # Try win32_ver() on win32 platforms
  1145.         if system == 'win32':
  1146.             release,version,csd,ptype = win32_ver()
  1147.             if release and version:
  1148.                 use_syscmd_ver = 0
  1149.             # Try to use the PROCESSOR_* environment variables
  1150.             # available on Win XP and later; see
  1151.             # http://support.microsoft.com/kb/888731 and
  1152.             # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
  1153.             if not machine:
  1154.                 machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
  1155.             if not processor:
  1156.                 processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
  1157.  
  1158.         # Try the 'ver' system command available on some
  1159.         # platforms
  1160.         if use_syscmd_ver:
  1161.             system,release,version = _syscmd_ver(system)
  1162.             # Normalize system to what win32_ver() normally returns
  1163.             # (_syscmd_ver() tends to return the vendor name as well)
  1164.             if system == 'Microsoft Windows':
  1165.                 system = 'Windows'
  1166.             elif system == 'Microsoft' and release == 'Windows':
  1167.                 # Under Windows Vista and Windows Server 2008,
  1168.                 # Microsoft changed the output of the ver command. The
  1169.                 # release is no longer printed.  This causes the
  1170.                 # system and release to be misidentified.
  1171.                 system = 'Windows'
  1172.                 if '6.0' == version[:3]:
  1173.                     release = 'Vista'
  1174.                 else:
  1175.                     release = ''
  1176.  
  1177.         # In case we still don't know anything useful, we'll try to
  1178.         # help ourselves
  1179.         if system in ('win32','win16'):
  1180.             if not version:
  1181.                 if system == 'win32':
  1182.                     version = '32bit'
  1183.                 else:
  1184.                     version = '16bit'
  1185.             system = 'Windows'
  1186.  
  1187.         elif system[:4] == 'java':
  1188.             release,vendor,vminfo,osinfo = java_ver()
  1189.             system = 'Java'
  1190.             version = string.join(vminfo,', ')
  1191.             if not version:
  1192.                 version = vendor
  1193.  
  1194.         elif os.name == 'mac':
  1195.             release,(version,stage,nonrel),machine = mac_ver()
  1196.             system = 'MacOS'
  1197.  
  1198.     # System specific extensions
  1199.     if system == 'OpenVMS':
  1200.         # OpenVMS seems to have release and version mixed up
  1201.         if not release or release == '0':
  1202.             release = version
  1203.             version = ''
  1204.         # Get processor information
  1205.         try:
  1206.             import vms_lib
  1207.         except ImportError:
  1208.             pass
  1209.         else:
  1210.             csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
  1211.             if (cpu_number >= 128):
  1212.                 processor = 'Alpha'
  1213.             else:
  1214.                 processor = 'VAX'
  1215.     if not processor:
  1216.         # Get processor information from the uname system command
  1217.         processor = _syscmd_uname('-p','')
  1218.  
  1219.     #If any unknowns still exist, replace them with ''s, which are more portable
  1220.     if system == 'unknown':
  1221.         system = ''
  1222.     if node == 'unknown':
  1223.         node = ''
  1224.     if release == 'unknown':
  1225.         release = ''
  1226.     if version == 'unknown':
  1227.         version = ''
  1228.     if machine == 'unknown':
  1229.         machine = ''
  1230.     if processor == 'unknown':
  1231.         processor = ''
  1232.  
  1233.     #  normalize name
  1234.     if system == 'Microsoft' and release == 'Windows':
  1235.         system = 'Windows'
  1236.         release = 'Vista'
  1237.  
  1238.     _uname_cache = system,node,release,version,machine,processor
  1239.     return _uname_cache
  1240.  
  1241. ### Direct interfaces to some of the uname() return values
  1242.  
  1243. def system():
  1244.  
  1245.     """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
  1246.  
  1247.         An empty string is returned if the value cannot be determined.
  1248.  
  1249.     """
  1250.     return uname()[0]
  1251.  
  1252. def node():
  1253.  
  1254.     """ Returns the computer's network name (which may not be fully
  1255.         qualified)
  1256.  
  1257.         An empty string is returned if the value cannot be determined.
  1258.  
  1259.     """
  1260.     return uname()[1]
  1261.  
  1262. def release():
  1263.  
  1264.     """ Returns the system's release, e.g. '2.2.0' or 'NT'
  1265.  
  1266.         An empty string is returned if the value cannot be determined.
  1267.  
  1268.     """
  1269.     return uname()[2]
  1270.  
  1271. def version():
  1272.  
  1273.     """ Returns the system's release version, e.g. '#3 on degas'
  1274.  
  1275.         An empty string is returned if the value cannot be determined.
  1276.  
  1277.     """
  1278.     return uname()[3]
  1279.  
  1280. def machine():
  1281.  
  1282.     """ Returns the machine type, e.g. 'i386'
  1283.  
  1284.         An empty string is returned if the value cannot be determined.
  1285.  
  1286.     """
  1287.     return uname()[4]
  1288.  
  1289. def processor():
  1290.  
  1291.     """ Returns the (true) processor name, e.g. 'amdk6'
  1292.  
  1293.         An empty string is returned if the value cannot be
  1294.         determined. Note that many platforms do not provide this
  1295.         information or simply return the same value as for machine(),
  1296.         e.g.  NetBSD does this.
  1297.  
  1298.     """
  1299.     return uname()[5]
  1300.  
  1301. ### Various APIs for extracting information from sys.version
  1302.  
  1303. _sys_version_parser = re.compile(
  1304.     r'([\w.+]+)\s*'
  1305.     '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
  1306.     '\[([^\]]+)\]?')
  1307.  
  1308. _jython_sys_version_parser = re.compile(
  1309.     r'([\d\.]+)')
  1310.  
  1311. _ironpython_sys_version_parser = re.compile(
  1312.     r'IronPython\s*'
  1313.     '([\d\.]+)'
  1314.     '(?: \(([\d\.]+)\))?'
  1315.     ' on (.NET [\d\.]+)')
  1316.  
  1317. _sys_version_cache = {}
  1318.  
  1319. def _sys_version(sys_version=None):
  1320.  
  1321.     """ Returns a parsed version of Python's sys.version as tuple
  1322.         (name, version, branch, revision, buildno, builddate, compiler)
  1323.         referring to the Python implementation name, version, branch,
  1324.         revision, build number, build date/time as string and the compiler
  1325.         identification string.
  1326.  
  1327.         Note that unlike the Python sys.version, the returned value
  1328.         for the Python version will always include the patchlevel (it
  1329.         defaults to '.0').
  1330.  
  1331.         The function returns empty strings for tuple entries that
  1332.         cannot be determined.
  1333.  
  1334.         sys_version may be given to parse an alternative version
  1335.         string, e.g. if the version was read from a different Python
  1336.         interpreter.
  1337.  
  1338.     """
  1339.     # Get the Python version
  1340.     if sys_version is None:
  1341.         sys_version = sys.version
  1342.  
  1343.     # Try the cache first
  1344.     result = _sys_version_cache.get(sys_version, None)
  1345.     if result is not None:
  1346.         return result
  1347.  
  1348.     # Parse it
  1349.     if sys_version[:10] == 'IronPython':
  1350.         # IronPython
  1351.         name = 'IronPython'
  1352.         match = _ironpython_sys_version_parser.match(sys_version)
  1353.         if match is None:
  1354.             raise ValueError(
  1355.                 'failed to parse IronPython sys.version: %s' %
  1356.                 repr(sys_version))
  1357.         version, alt_version, compiler = match.groups()
  1358.         branch = ''
  1359.         revision = ''
  1360.         buildno = ''
  1361.         builddate = ''
  1362.  
  1363.     elif sys.platform[:4] == 'java':
  1364.         # Jython
  1365.         name = 'Jython'
  1366.         match = _jython_sys_version_parser.match(sys_version)
  1367.         if match is None:
  1368.             raise ValueError(
  1369.                 'failed to parse Jython sys.version: %s' %
  1370.                 repr(sys_version))
  1371.         version, = match.groups()
  1372.         branch = ''
  1373.         revision = ''
  1374.         compiler = sys.platform
  1375.         buildno = ''
  1376.         builddate = ''
  1377.  
  1378.     else:
  1379.         # CPython
  1380.         match = _sys_version_parser.match(sys_version)
  1381.         if match is None:
  1382.             raise ValueError(
  1383.                 'failed to parse CPython sys.version: %s' %
  1384.                 repr(sys_version))
  1385.         version, buildno, builddate, buildtime, compiler = \
  1386.               match.groups()
  1387.         if hasattr(sys, 'subversion'):
  1388.             # sys.subversion was added in Python 2.5
  1389.             name, branch, revision = sys.subversion
  1390.         else:
  1391.             name = 'CPython'
  1392.             branch = ''
  1393.             revision = ''
  1394.         builddate = builddate + ' ' + buildtime
  1395.  
  1396.     # Add the patchlevel version if missing
  1397.     l = string.split(version, '.')
  1398.     if len(l) == 2:
  1399.         l.append('0')
  1400.         version = string.join(l, '.')
  1401.  
  1402.     # Build and cache the result
  1403.     result = (name, version, branch, revision, buildno, builddate, compiler)
  1404.     _sys_version_cache[sys_version] = result
  1405.     return result
  1406.  
  1407. def _test_sys_version():
  1408.  
  1409.     _sys_version_cache.clear()
  1410.     for input, output in (
  1411.         ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]',
  1412.          ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')),
  1413.         ('IronPython 1.0.60816 on .NET 2.0.50727.42',
  1414.          ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')),
  1415.         ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42',
  1416.          ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')),
  1417.         ):
  1418.         parsed = _sys_version(input)
  1419.         if parsed != output:
  1420.             print (input, parsed)
  1421.  
  1422. def python_implementation():
  1423.  
  1424.     """ Returns a string identifying the Python implementation.
  1425.  
  1426.         Currently, the following implementations are identified:
  1427.         'CPython' (C implementation of Python),
  1428.         'IronPython' (.NET implementation of Python),
  1429.         'Jython' (Java implementation of Python).
  1430.  
  1431.     """
  1432.     return _sys_version()[0]
  1433.  
  1434. def python_version():
  1435.  
  1436.     """ Returns the Python version as string 'major.minor.patchlevel'
  1437.  
  1438.         Note that unlike the Python sys.version, the returned value
  1439.         will always include the patchlevel (it defaults to 0).
  1440.  
  1441.     """
  1442.     return _sys_version()[1]
  1443.  
  1444. def python_version_tuple():
  1445.  
  1446.     """ Returns the Python version as tuple (major, minor, patchlevel)
  1447.         of strings.
  1448.  
  1449.         Note that unlike the Python sys.version, the returned value
  1450.         will always include the patchlevel (it defaults to 0).
  1451.  
  1452.     """
  1453.     return tuple(string.split(_sys_version()[1], '.'))
  1454.  
  1455. def python_branch():
  1456.  
  1457.     """ Returns a string identifying the Python implementation
  1458.         branch.
  1459.  
  1460.         For CPython this is the Subversion branch from which the
  1461.         Python binary was built.
  1462.  
  1463.         If not available, an empty string is returned.
  1464.  
  1465.     """
  1466.  
  1467.     return _sys_version()[2]
  1468.  
  1469. def python_revision():
  1470.  
  1471.     """ Returns a string identifying the Python implementation
  1472.         revision.
  1473.  
  1474.         For CPython this is the Subversion revision from which the
  1475.         Python binary was built.
  1476.  
  1477.         If not available, an empty string is returned.
  1478.  
  1479.     """
  1480.     return _sys_version()[3]
  1481.  
  1482. def python_build():
  1483.  
  1484.     """ Returns a tuple (buildno, builddate) stating the Python
  1485.         build number and date as strings.
  1486.  
  1487.     """
  1488.     return _sys_version()[4:6]
  1489.  
  1490. def python_compiler():
  1491.  
  1492.     """ Returns a string identifying the compiler used for compiling
  1493.         Python.
  1494.  
  1495.     """
  1496.     return _sys_version()[6]
  1497.  
  1498. ### The Opus Magnum of platform strings :-)
  1499.  
  1500. _platform_cache = {}
  1501.  
  1502. def platform(aliased=0, terse=0):
  1503.  
  1504.     """ Returns a single string identifying the underlying platform
  1505.         with as much useful information as possible (but no more :).
  1506.  
  1507.         The output is intended to be human readable rather than
  1508.         machine parseable. It may look different on different
  1509.         platforms and this is intended.
  1510.  
  1511.         If "aliased" is true, the function will use aliases for
  1512.         various platforms that report system names which differ from
  1513.         their common names, e.g. SunOS will be reported as
  1514.         Solaris. The system_alias() function is used to implement
  1515.         this.
  1516.  
  1517.         Setting terse to true causes the function to return only the
  1518.         absolute minimum information needed to identify the platform.
  1519.  
  1520.     """
  1521.     result = _platform_cache.get((aliased, terse), None)
  1522.     if result is not None:
  1523.         return result
  1524.  
  1525.     # Get uname information and then apply platform specific cosmetics
  1526.     # to it...
  1527.     system,node,release,version,machine,processor = uname()
  1528.     if machine == processor:
  1529.         processor = ''
  1530.     if aliased:
  1531.         system,release,version = system_alias(system,release,version)
  1532.  
  1533.     if system == 'Windows':
  1534.         # MS platforms
  1535.         rel,vers,csd,ptype = win32_ver(version)
  1536.         if terse:
  1537.             platform = _platform(system,release)
  1538.         else:
  1539.             platform = _platform(system,release,version,csd)
  1540.  
  1541.     elif system in ('Linux',):
  1542.         # Linux based systems
  1543.         distname,distversion,distid = dist('')
  1544.         if distname and not terse:
  1545.             platform = _platform(system,release,machine,processor,
  1546.                                  'with',
  1547.                                  distname,distversion,distid)
  1548.         else:
  1549.             # If the distribution name is unknown check for libc vs. glibc
  1550.             libcname,libcversion = libc_ver(sys.executable)
  1551.             platform = _platform(system,release,machine,processor,
  1552.                                  'with',
  1553.                                  libcname+libcversion)
  1554.     elif system == 'Java':
  1555.         # Java platforms
  1556.         r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
  1557.         if terse or not os_name:
  1558.             platform = _platform(system,release,version)
  1559.         else:
  1560.             platform = _platform(system,release,version,
  1561.                                  'on',
  1562.                                  os_name,os_version,os_arch)
  1563.  
  1564.     elif system == 'MacOS':
  1565.         # MacOS platforms
  1566.         if terse:
  1567.             platform = _platform(system,release)
  1568.         else:
  1569.             platform = _platform(system,release,machine)
  1570.  
  1571.     else:
  1572.         # Generic handler
  1573.         if terse:
  1574.             platform = _platform(system,release)
  1575.         else:
  1576.             bits,linkage = architecture(sys.executable)
  1577.             platform = _platform(system,release,machine,processor,bits,linkage)
  1578.  
  1579.     _platform_cache[(aliased, terse)] = platform
  1580.     return platform
  1581.  
  1582. ### Command line interface
  1583.  
  1584. if __name__ == '__main__':
  1585.     # Default is to print the aliased verbose platform string
  1586.     terse = ('terse' in sys.argv or '--terse' in sys.argv)
  1587.     aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
  1588.     print platform(aliased,terse)
  1589.     sys.exit(0)
  1590.